package com.ctsi.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctsi.common.util.Search;
import com.ctsi.system.constant.DictConstant;
import com.ctsi.system.entity.EmpPos;
import com.ctsi.system.entity.Pos;
import com.ctsi.system.mapper.EmpPosMapper;
import com.ctsi.system.service.IEmpPosService;
import com.ctsi.system.service.IPosService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 员工职位关联表 服务实现类
 * </p>
 *
 * @author wang xiao xiang
 */
@Service
@AllArgsConstructor
public class EmpPosServiceImpl extends ServiceImpl<EmpPosMapper, EmpPos> implements IEmpPosService {

	private final IPosService posService;

	@Override
	public IPage<EmpPos> listPage(Page page, Search search) {
		LambdaQueryWrapper<EmpPos> queryWrapper = new LambdaQueryWrapper<>();
		return this.baseMapper.selectPage(page, queryWrapper);
	}

	@Override
	public List<Dict> getEmpPosDictList(Long empId, boolean isFillId) {
		List<Dict> dictList = CollectionUtil.newArrayList();
		this.list(Wrappers.<EmpPos>query().lambda()
				.eq(EmpPos::getEmpId, empId)).forEach(empPos -> {
			Dict dict = Dict.create();
			Long posId = empPos.getPosId();
			Pos pos = posService.getById(posId);
			dict.put(DictConstant.POS_CODE_DICT_KEY, pos.getCode());
			dict.put(DictConstant.POS_NAME_DICT_KEY, pos.getName());
			if (isFillId) {
				dict.put(DictConstant.POS_ID_DICT_KEY, posId);
			}
			dictList.add(dict);
		});
		return dictList;
	}

	@Override
	public boolean setEmpPos(Long empId, List<Long> posIdList) {
		// 删除员工职位信息
		this.remove(Wrappers.<EmpPos>query().lambda().eq(EmpPos::getEmpId, empId));
		// 保存员工职位信息
		posIdList.forEach(posId -> {
			EmpPos empPos = new EmpPos();
			empPos.setEmpId(empId);
			empPos.setPosId(posId);
			this.save(empPos);
		});
		return Boolean.TRUE;
	}
}
